import cv2
import numpy as np
import requests
import re


def blockPuzzle(bgUrl, tpUrl):

    bgRsp = requests.get(bgUrl)
    bgImg = cv2.imdecode(np.fromstring(bgRsp.content, np.uint8), 1)

    tpRsp = requests.get(tpUrl)
    tpImg = cv2.imdecode(np.fromstring(tpRsp.content, np.uint8), 1)

    # 识别图片边缘
    bgEdge = cv2.Canny(bgImg, 100, 200)
    tpEdge = cv2.Canny(tpImg, 100, 200)

    # 转换图片格式
    bgPic = cv2.cvtColor(bgEdge, cv2.COLOR_GRAY2RGB)
    tpPic = cv2.cvtColor(tpEdge, cv2.COLOR_GRAY2RGB)

    # 缺口匹配
    res = cv2.matchTemplate(bgPic, tpPic, cv2.TM_CCOEFF_NORMED)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)  # 寻找最优匹配

    return max_loc[0]


def verify_car_number(number: str) -> bool:
    number = number.strip()
    pattern = r"^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}.{5,6}$"
    return re.match(pattern, number) is not None


if __name__ == "__main__":
    blockPuzzle(
        "https://osscaptcha-cdn.keytop.cn/jigsaw/BlockPuzzle-IMG:21:42",
        "https://osscaptcha-cdn.keytop.cn/origin/BlockPuzzle-IMG:21:42",
    )
